package com.desheng.j2ee.mvcframework.annotation.dispatcher.v1;

import com.desheng.j2ee.mvcframework.annotation.annotation.*;
import com.desheng.j2ee.mvcframework.annotation.configuration.Configuration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
public class HttpServletDispatcher extends HttpServlet {
    private Properties contextProperties = new Properties();
    private List<String> classNames = new ArrayList<String>();
    //bean容器
    private Map<String, Object> ioc = new HashMap<String, Object>();
    private Map<String, Method> handlerMapping = new HashMap<String, Method>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6. 委派，根据url去找到一个对应的Method并通过response返回
        try {
            doDispatcher(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception,Detail : " + Arrays.toString(e.getStackTrace()));
        }
    }
    private void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");
        if(!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found!!!");
            return;
        }
        Map<String, String[]> params = req.getParameterMap();
        Method method = this.handlerMapping.get(url);
        //获取形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] paramValues = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> parameterType = parameterTypes[i];
            if(parameterType == HttpServletRequest.class) {
                paramValues[i] = req;
            } else if(parameterType == HttpServletResponse.class) {
                paramValues[i] = resp;
            } else if(parameterType == String.class){
                //运行时获取值
                Annotation[][] pas = method.getParameterAnnotations();
                for (Annotation annotation : pas[i]) {
                    if(annotation instanceof DSRequestParam) {
                        String paramName = ((DSRequestParam) annotation).value();
                        if(!"".equals(paramName.trim())) {
                            String paramVal = Arrays.toString(params.get(paramName))
                                        .replaceAll("\\[|\\]", "")
                                        .replaceAll("\\s+", ",");
                            paramValues[i] = paramVal;
                        }
                    }
                }
            } else if(parameterType == int.class || parameterType == Integer.class) {
                Annotation[][] pas = method.getParameterAnnotations();
                for (Annotation annotation : pas[i]) {
                    if(annotation instanceof DSRequestParam) {
                        String paramName = ((DSRequestParam) annotation).value();
                        if(!"".equals(paramName.trim())) {
                            String paramVal = Arrays.toString(params.get(paramName))
                                    .replaceAll("\\[|\\]", "")
                                    .replaceAll("\\s+", ",");
                            paramValues[i] = Integer.valueOf(paramVal);
                        }
                    }
                }
            }
        }
        //执行方法
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(ioc.get(beanName), paramValues);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        loadConfig(config.getInitParameter("configuration"));
        //2、扫描配置类
        doScanner(contextProperties.getProperty(Configuration.BASE_SCAN_PACKAGE));
        //3、初始化扫描到的泪，并放入IOC容器之中
        doInstance();
        //4、完成自动化依赖注入
        doAutowired();
        //5、初始化handlerMapping
        doInitHandlerMapping();
        System.out.println("Spring framework has bean inited. ");
    }
    private void doInitHandlerMapping() {
        if(ioc.isEmpty()){return;}
        for (Map.Entry<String,Object> me : ioc.entrySet()) {
            Class<?> clazz = me.getValue().getClass();
            if(!clazz.isAnnotationPresent(DSController.class)){continue;}
            //相当于提取 class上配置的url
            String baseUrl = "";
            if(clazz.isAnnotationPresent(DSRequestMapping.class)) {
                DSRequestMapping reqMapping = clazz.getAnnotation(DSRequestMapping.class);
                baseUrl = reqMapping.value();
            }
            //只获取public的方法
            for(Method method: clazz.getMethods()) {
                if(!method.isAnnotationPresent(DSRequestMapping.class)){continue;}
                DSRequestMapping reqMapping = method.getAnnotation(DSRequestMapping.class);
                String url = (baseUrl + "/" + reqMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);
                System.out.println("mapping: " + url + ">>>>" + method);
            }
        }
    }
    private void doAutowired() {
        if(ioc.isEmpty()){return;}
        for(Map.Entry<String, Object> me : ioc.entrySet()) {
            //把所有的包括private/protected/default/public修饰字段都提取出来
            for (Field field : me.getValue().getClass().getDeclaredFields()) {
                if(!field.isAnnotationPresent(DSAutowired.class)) {continue;}
                DSAutowired autowired = field.getAnnotation(DSAutowired.class);
                //如果用户没有自定的beanName，就默认根据类型注入
                String beanName = autowired.value().trim();
                if("".equals(beanName)) {
                    beanName = toLowerFirstCase(field.getType().getSimpleName());
                }
                //暴力反射
                field.setAccessible(true);
                try {
                    field.set(me.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private void doInstance() {
        if(classNames.isEmpty()){return;}
        for (String className : classNames) {
            try {
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(DSController.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                } else if(clazz.isAnnotationPresent(DSService.class)) {
                    //1、在多个包下出现相同的类名，只能自己起一个全局唯一的名字
                    //自定义命名
                    String beanName = clazz.getAnnotation(DSService.class).value();
                    if("".equals(beanName.trim())) {
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }
                    //2、默认的类名首字母小写
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    //3、如果是接口
                    //判断有多个实现类，如果只有一个，默认就选择这个实现类，如果有多个，就只能异常
                    for (Class<?> i : clazz.getInterfaces()) {
                        if(ioc.containsKey(toLowerFirstCase(i.getSimpleName()))) {
                            throw new Exception("the " + i.getName() + " is exists !");
                        }
                        ioc.put(toLowerFirstCase(i.getSimpleName()), instance);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private String toLowerFirstCase(String beanName) {
        char[] chs = beanName.toCharArray();
        chs[0] += 32;
        return new String(chs);
    }
    private void doScanner(String scanPackage) {
        //将包路径转化为文件夹路径
        String packagePath = scanPackage.replaceAll("\\.", "/");
        URL url = this.getClass().getClassLoader().getResource(packagePath);
        File classPath = new File(url.getFile());
        //以此对各个class进行初始化
        for (File file : classPath.listFiles()) {
            if(file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                if(!file.getName().endsWith(".class")){continue;}
                //全类名=报名.类名
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }
    private void loadConfig(String configuration) {
        InputStream ins = null;
        try {
            ins = this.getClass().getClassLoader().getResourceAsStream(configuration.replace("classpath:", ""));
            contextProperties.load(ins);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(ins != null) {
                    ins.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
